<?php

/**
 * This is the model class for table "{{users}}".
 *
 * The followings are the available columns in table '{{users}}':
 * @property integer $id
 * @property string $password
 * @property string $salt
 * @property string $email
 * @property string $status
 * @property integer $date_created
 * @property string $type
 * @property string $firstname
 * @property string $lastname
 * @property string $address
 * @property string $photo
 * @property integer $author_id
 * @property int $birthday 
 * @property string $phone
 * @property string $username
 */
class Users extends MyActiveRecord {

    const SUPER_ADMIN = 1;
    
    const TYPE_ADMIN = 'Admin';
    const TYPE_STAFF = 'Staff';
    const TYPE_CUSTOMER = 'Customer';

    const STATUS_BLOCK = 0;
    const STATUS_ACTIVE = 1;

    public $repassword; //Repeat Password
    public $new_pass; //New password
    public $old_pass; //Old password
    public $renewpass; //Repeat New Password
    public $verifyCode; // Capcha
    public $staff_group;
    public $biz_id; // Business ID

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Users the static model class
     */

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @param $email
     * @return Users
     */
    public function findByEmail($email) {
        $crite = new CDbCriteria();

        $crite->compare('email', $email);
        $crite->compare('type', Users::TYPE_CUSTOMER);

        $user = Users::model()->find($crite);

        if (NULL == $user) {
            return FALSE;
        } else {
            return $user;
        }
    }

    public function verifyPassword($password) {
        return ($this->hashPassword($password, $this->salt) == $this->password);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{users}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('username', 'required'),
            array('email', 'email'),
            array('author_id', 'numerical'),
            array('password, new_pass', 'length', 'min' => 6),
            array('username, firstname, lastname, password, repassword, phone', 'length', 'max' => 32),
            array('type, address', 'length', 'max' => 255),
            array('address', 'safe'),
            //Change password
//            array('old_pass, new_pass, renewpass', 'required', 'on' => 'changepassword'),
//            array('old_pass', 'checkOldPassword', 'on' => 'changepassword'),
//            array('renewpass', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'changepassword'),
            //Forgot password
//            array('email', 'required', 'on' => 'forgotpwd'),
//            array('email', 'email', 'on' => 'forgotpwd'),
//            array('renewpass', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'forgotpass'),
            //Reset password
            array('new_pass, repassword', 'required', 'on' => 'resetpwd'),
            array('repassword, new_pass', 'length', 'min' => 6),
            array('repassword', 'compare', 'compareAttribute' => 'new_pass', 'message' => Yii::t('user','Password repeated is incorrect')),
            //Change Email
//            array('newmail, renewmail', 'required', 'on' => 'changeemail'),
//            array('renewmail', 'compare', 'compareAttribute' => 'newmail', 'on' => 'changeemail'),
//            array('newmail, renewmail', 'email', 'on' => 'changeemail'),
            // Admin
            array(
                'username, firstname, lastname',
                'required',
                'on' => 'edit'
            ),
            array(
                'username, new_pass, firstname, lastname, status, repassword',
                'required',
                'on' => 'create'
            ),
            array(
                'birthday, photo',
                'safe',
            ),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, firstname, lastname, address, type, status, email, author_id, date_created', 'safe', 'on' => 'search'),
//            array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'on' => 'signup'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        $relations = parent::relations();
        $relations['author'] = array(
            self::BELONGS_TO, 'Users', 'author_id',
        );
        return $relations;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'username' => Yii::t('user', 'Username'),
            'password' => Yii::t('user', 'Password'),
            'email' => Yii::t('user', 'Email'),
            'type' => Yii::t('user', 'Type'),
            'date_created' => Yii::t('user', 'Date Created'),
            'new_pass' => Yii::t('user', 'Password'),
            'old_pass' => Yii::t('user', 'Old password'),
            'repassword' => Yii::t('user', 'Password repeat'),
            'renewpass' => Yii::t('user', 'Repeat new password'),
            'verifyCode' => Yii::t('user', 'Verify Code'),
            'address' => Yii::t('user', 'Address'),
            'phone' => Yii::t('user', 'Phone'),
            'firstname' => Yii::t('user', 'First Name'),
            'lastname' => Yii::t('user', 'Last Name'),
            'photo' => Yii::t('user', 'Photo'),
            'status' => Yii::t('user', 'Status'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('username', $this->username, true);
        $criteria->compare('password', $this->password, true);
        $criteria->compare('salt', $this->salt, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('type', $this->type, true);
        $criteria->compare('status', $this->status, true);
        $criteria->compare('date_created', $this->date_created, true);
        $criteria->compare('firstname', $this->firstname, true);
        $criteria->compare('lastname', $this->lastname, true);
        $criteria->compare('address', $this->address, true);
        $criteria->compare('phone', $this->phone, true);
        $criteria->compare('photo', $this->photo, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Checks if the given password is correct.
     * @param string the password to be validated
     * @return boolean whether the password is valid
     */
    public function validatePassword($password) {
        return ($this->hashPassword($password, $this->salt) == $this->password);
    }

    public function validateRole($role) {
        return ($role == $this->type);
    }

    /**
     * Checks if the given password is correct.
     * @param string the password to be validated
     * @return boolean whether the password is valid
     */
    public function checkOldPassword($attribute) {
        if ($this->hashPassword($this->{$attribute}, $this->salt) === $this->password)
            return TRUE;
        else {
            $this->addError($attribute, Yii::t('adminuser', '{object} is incorrect', array(
                        '{object}' => $this->getAttributeLabel($attribute),
            )));
            return FALSE;
        }
    }

    /**
     * Generates the password hash.
     * @param string password
     * @param string salt
     * @return string hash
     */
    public function hashPassword($password, $salt) {
        return md5($salt . $password);
    }

    /**
     * Generates a salt that can be used to generate a password hash.
     * @return string the salt
     */
    public function generateSalt() {
        return uniqid('', true);
    }

    public function beforeSave() {
        if (parent::beforeSave()) {
            if ($this->new_pass != '') {
                $this->salt = $this->generateSalt();
                $this->password = $this->hashPassword($this->new_pass, $this->salt);
            }
            
            return TRUE;
        } else
            return FALSE;
    }

    function afterSave() {

        if (parent::afterSave()) {
            $auth = Yii::app()->authManager;

            // Xóa các quy�?n đã gán trước đây đi
            if ($auth->getAuthAssignments($this->id))
                foreach ($auth->getAuthAssignments($this->id) as $item)
                    $auth->revoke($item->itemName, $this->id);

            // Gán quy�?n mới 
            $auth->assign($this->type, $this->id);
            
            if ($this->birthday != '') {
                $this->birthday = strtotime($this->birthday);
            }
            return TRUE;
        }
        else {
            return FALSE;
        }
    }

    /**
     * 
     * @param type $act name of action
     * @param type $con name of controller
     * @return boolean
     */
    static function checkAccess($act, $con) {
//        return TRUE;
        $act = ucfirst($act);
        $con = ucfirst($con);
        //CVarDumper::dump($act);
        if (Yii::app()->user->checkAccess("$con.*"))
            return TRUE;

        if (Yii::app()->user->checkAccess("$con.$act"))
            return TRUE;
        return FALSE;
    }

    public static function getArrayType() {
        return array(
            self::TYPE_ADMIN => Yii::t('user', 'Administrator'),
            self::TYPE_STAFF => Yii::t('user', 'Staff'),
            self::TYPE_CUSTOMER => Yii::t('user', 'Customer'),
        );
    }

    public static function getArrayStatus() {
        return array(
            self::STATUS_ACTIVE => 'Active',
            self::STATUS_BLOCK => 'Block',
        );
    }

    public function getAvartBySize($width, $height) {
        
        if (!$this->photo) {
            return Yii::app()->controller->assetDir . 'img/avatar-blank.jpg';
        }

        
        if (strstr($this->photo, 'http') !=FALSE ){
            return $this->photo;
        }
            
        $file = Yii::getPathOfAlias('webroot') . '/' . $this->photo;
        $path = Yii::getPathOfAlias('webroot') . '/files/user/';

        if (!file_exists($file)) {
            return Yii::app()->controller->assetDir . 'img/avatar-blank.jpg';
        }
       
        $path_parts = pathinfo($file);

        $extesion = $path_parts['extension'];
        $file_name = $path_parts['filename'] . "_w" . $width . 'h' . $height . '.' . $extesion;

        if (!file_exists($path.$file_name) AND !is_file($path.$file_name)) {
            
            $thumb = Yii::app()->phpThumb->create($file);
            $thumb->adaptiveResize($width, $height);
            $thumb->save($path . '/' . $file_name);
        }

        return Yii::app()->baseUrl . '/files/user' . '/' . $file_name;
    }

    public function getPublicPhoto($absolute = FALSE) {
        if ($this->photo) {
            if (strstr($this->photo, 'http') !== FALSE) {
                return $this->photo;
            } else {
                return $this->photo;
            }
        } else {
            return $absolute ? baseUrl() . Yii::app()->controller->assetDir . '/img/avatar-blank.jpg': Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
        }
    }

    public function getStatusLabel() {
        if (!$this->hasAttribute("status"))
            return '';

        $labelClass = 'label ';
        switch ($this->status) {
            case self::STATUS_ACTIVE:
                $labelClass .= 'label-success';
                break;

            case self::STATUS_BLOCK:
                $labelClass .= 'label-important';
                break;

            default:
                break;
        }
        $labels = self::getArrayStatus();
        $label = isset($labels[$this->status]) ? $labels[$this->status] : $this->status;
        return "<span class='$labelClass'>$label</span>";
    }

    public static function getCreateUrl($type) {
        return Yii::app()->createUrl(strtolower($type) . "/create");
    }

    public function getViewUrl() {
        return Yii::app()->createUrl(strtolower($this->type) . "/view", array(
                    "pk" => $this->ukey,
        ));
    }

    public function getEditUrl() {
        if ($this->id == self::SUPER_ADMIN)
            return FALSE;

        return Yii::app()->createUrl(strtolower($this->type) . "/edit", array(
                    "pk" => $this->ukey,
        ));
    }

    public function getDeleteUrl() {
        if ($this->id == self::SUPER_ADMIN)
            return FALSE;

        return Yii::app()->createUrl(strtolower($this->type) . "/delete", array(
                    "pk" => $this->ukey,
        ));
    }

    public function getName()
    {
        if (!empty($this->username))
            return $this->username;
        else if (!empty ($this->firstname))
            return "$this->firstname $this->lastname";
    }

    public function formartDate() {
        echo date('F d Y', $this->date_created);
    }

}
